﻿using CMS.AOP;
using CMS.DataAccess;
using CMS.Excep;
using CMS.Model;
using CMS.Utils;

namespace CMS.ServiceProvider
{
    public class BaseServiceProvider<T> where T : BaseModel, new()
    {
        public BaseServiceProvider()
        {
            instance = ServiceLoader.GetService<DbInstance>(); 
            qryInstance = new DbQuery<T>();
            udpInstance = new DbUpdater<T>();
        }
        protected DbQuery<T> qryInstance;
        protected DbUpdater<T> udpInstance;
        protected DbInstance instance;
        protected List<IDefaultValueSetter<T>> defValSetters = new List<IDefaultValueSetter<T>>();
        public void AddDefaultValueSetter(IDefaultValueSetter<T> s)
        { 
            defValSetters.Add(s);
        }
        public virtual T Get(string pk)
        {
            var r = qryInstance.Get(pk);
            return r;
        }
        public virtual void Save(T data)
        {
            foreach(var s in defValSetters)
            {
                s.SetValue(data);
            }
            udpInstance.Save(data);
        }
        public virtual List<T> List(CondCollection cond, int index, int pageSize, out int total)
        {
            return qryInstance.Where(cond).OrderBy(cond.OrderBy.ToArray()).ToPageList(index, pageSize,out total);
        }
        public virtual List<T> List(CondCollection cond)
        {
            return qryInstance.Where(cond).OrderBy(cond.OrderBy.ToArray()).List();
        }
        public virtual void Delete(string pk)
        {
            udpInstance.Delete(pk);
        }
    }
}
